package com.example.testapplication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;

import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URI;

public class AsyncTaskTestActivity extends ApplicationActivity{

    private File apkFile;
    private ProgressDialog dialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async);
    }

    public void downloadApk(View view){
        // 启动异步任务处理
        new AsyncTask<Void,Integer,Void>(){
            // 1.主线程 显示提示视图
            protected void onPreExecute(Void unused) {

                dialog = new ProgressDialog(AsyncTaskTestActivity.this);
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                dialog.show();
                //准备用于保存APK文件的File对象 : /storage/sdcard/Android/package_name/files/xxx.apk
                apkFile = new File(getExternalFilesDir(null), "update.apk");

            }
             // 2.分线程，网络请求
            //完成任务的主要工作，通常需要较长的时间
            @Override
            protected Void doInBackground(Void... voids) {

                try {
                    // 1.请求接口
                    String path = "http://192.168.0.105:8080/example/L04_datastorage.apk";
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // 2. 设置
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(10000);
                    //3.连接
                    connection.connect();
                    //4.请求并得到响应码200
                    int responseCode = connection.getResponseCode();
                    if(responseCode == 200){
                        // 设置dialog的最大进度
                        dialog.setMax(connection.getContentLength());
                        // 5.得到包含APK文件数据的InputStream
                        InputStream is = connection.getInputStream();
                        // 6.创建指向apk
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        // 7.边度边写
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) !=-1){
                            fos.write(buffer,0,len);
                            // 发布当前进度
                            publishProgress(len);

                            // 模拟网速慢
                            SystemClock.sleep(50);
                        }
                        fos.close();
                        is.close();
                    }
                    // 9.下载完成，关闭，进入
                    connection.disconnect();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }
            // 3.主线程，更新界面
            protected void onPostExecute(Void resut){
                dialog.dismiss();
                installAPK();

            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                dialog.incrementProgressBy(values[0]);
            }
        }.execute();
    }
    /**
     * 启动安装APK
     */
    private void installAPK() {
        Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
